/**
 * Project Name:九色鹿
 * File Name:CommonController.java
 * Package Name:com.fxp.project.jiuselu.web.business.v1.controller.common
 * Date:2021-09-12 3:39 下午
 * Copyright (c) 2021, Jason.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.web.business.v1.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.entity.BaseSmsMessage;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.commons.file.FileUploadUtils;
import com.fxp.project.jiuselu.commons.utils.CommonUtil;
import com.fxp.project.jiuselu.sms.context.SmsServiceContext;
import com.fxp.project.jiuselu.web.base.controller.BaseController;
import com.fxp.project.jiuselu.web.base.request.ReqBase;
import com.fxp.project.jiuselu.web.business.v1.pojo.UserInfoVo;
import com.fxp.project.jiuselu.web.business.v1.request.sms.ReqMessage;
import com.fxp.project.jiuselu.web.config.CustomerApiConfig;
import com.fxp.project.jiuselu.web.domain.CommonResult;
import com.fxp.project.jiuselu.web.models.common.service.IJslLogisticCompanyService;
import com.fxp.project.jiuselu.web.models.order.service.IJslLogisticAreaService;
import com.fxp.project.jiuselu.web.models.user.entity.JslSaleInfo;
import com.fxp.project.jiuselu.web.models.user.entity.JslUser;
import com.fxp.project.jiuselu.web.models.user.service.IJslSaleInfoService;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * ClassName: CommonController<br/>
 * Function: 开放式的配置方法<br/>
 * Date: 2021-09-12 3:39 下午<br/>
 *
 * @author Jason.Wang
 * @version 1.0.0.0
 * @see
 * @since JDK 8
 */
@RestController
@RequestMapping("/v1/common")
public class CommonController extends BaseController {

    @Autowired
    SmsServiceContext smsServiceContext;
    @Autowired
    IJslUserService jslUserService;
    @Autowired
    CustomerApiConfig customerApiConfig;
    @Autowired
    IJslLogisticCompanyService jslLogisticCompanyService;
    @Autowired
    IJslSaleInfoService jslSaleInfoService;
    /**
     * sendMessage: 发送短信<br/>
     *
     * @param reqMessage
     * @param result
     * @return
     * @author Jason.Wang
     * @createTime 2020/4/1 23:44
     */
    @RequestMapping("send/sms")
    @CrossOrigin
    public CommonResult<String> sendMessage(@RequestBody @Validated ReqMessage reqMessage, BindingResult result) {
        super.checkBindResult(result);
        return sendSmsCode(reqMessage);
    }

    /**
     * sendLoginCode: 发送登录使用的验证码<br/>
     *
     * @param reqMessage
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/9/14 10:04 下午
     */
    @RequestMapping("login/code")
    @CrossOrigin
    public CommonResult<String> sendLoginCode(@RequestBody @Validated ReqMessage reqMessage, BindingResult result) {
        super.checkBindResult(result);
        // 当前对象为手机号+验证码、手机号+密码登录时需要检查当前用户是否存在
        List<JslUser> list = jslUserService.list(new QueryWrapper<JslUser>().lambda().eq(JslUser::getUserPhone, reqMessage.getMobile()));
        if (list.size()==0) return CommonResult.failed("当前手机号未注册");
        JslUser jslUser = jslUserService.selectByUserPhoneAndLevle(reqMessage.getMobile(),reqMessage.getLevel());
        if(jslUser.getEnable()==0){
            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"系统识别该账号异常，如有疑问请联系客服400-8388-326");
        }
        if(reqMessage.getLevel()==1){
            JslSaleInfo saleInfo = jslSaleInfoService.getOne(new QueryWrapper<JslSaleInfo>().eq("sale_phone", reqMessage.getMobile()));
            if(saleInfo.getStatus()==2){
                throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"审核未通过,拒绝原因: "+saleInfo.getRemark()+",请重新提交记录");
            }else if(saleInfo.getStatus()==0){
                throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"您的申请已提交,请耐心等待审核,审核预计时长 : 3天");
            }
        }
        return sendSmsCode(reqMessage);
    }

    /**
     * sendRegCode: 发送注册用验证码<br/>
     *
     * @param reqMessage
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/9/14 10:05 下午
     */
    @RequestMapping("reg/code")
    @CrossOrigin
    public CommonResult<String> sendRegCode(@RequestBody @Validated ReqMessage reqMessage, BindingResult result) {
        super.checkBindResult(result);
        // 当前对象为手机号+验证码、手机号+密码登录时需要检查当前用户是否存在
//        JslUser jslUser = jslUserService.selectByUserPhone(reqMessage.getMobile());
//        if (null != jslUser) {
//            return CommonResult.validateFailed("当前手机号已注册，请直接登录");
//        }
        List<JslUser> list = jslUserService.list(new QueryWrapper<JslUser>().lambda().eq(JslUser::getUserPhone, reqMessage.getMobile()).eq(JslUser::getLevel,0));
        if (list.size()!=0) {
            return CommonResult.failed("当前手机号已注册，请直接登录");
        }
        return sendSmsCode(reqMessage);
    }

    /**
     * sendSmsCode: 发送手机短信<br/>
     *
     * @param reqMessage
     * @return
     * @author Kai.Wang
     * @date 2021/11/1 10:33
     */
    private CommonResult<String> sendSmsCode(@Validated @RequestBody ReqMessage reqMessage) {
        BaseSmsMessage baseSmsMessage = BaseSmsMessage.getEnumByType(reqMessage.getType());
        String code = CommonUtil.smsCode();
        super.setMobileCode(reqMessage.getMobile(), code);
//        return CommonResult.success(code);
        if (smsServiceContext.sendSms(baseSmsMessage.getKey(), reqMessage.getMobile(), String.format(baseSmsMessage.getMessage(), code, smsOften))) {
            super.setMobileCode(reqMessage.getMobile(), code);
            return CommonResult.success(code);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * uploadFile: 上传文件接口<br/>
     *
     * @param file
     * @return
     * @author Kai.Wang
     * @date 2021/11/10 15:36
     */
    @PostMapping("/upload")
    @CrossOrigin
    public CommonResult uploadFile(MultipartFile file) throws IOException {
        String filePath = customerApiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(customerApiConfig.getProfile(), filePath, file);
        String url = "profile" + fileName;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileName", file.getOriginalFilename());
        jsonObject.put("url", url);
        return CommonResult.success(jsonObject);
    }

    /**
     * logisticCompany: 获取当前的快递公司列表<br/>
     * @author Jason.Wang
     * @date 2022/1/1 22:04
     * @param reqBase
     * @return
     */
    @PostMapping("logistic/company")
    @CrossOrigin
    public CommonResult logisticCompany(@Validated @RequestBody ReqBase reqBase){
        return CommonResult.success(jslLogisticCompanyService.list());
    }
}
